package com.codechuan.hallo_web.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.codechuan.hallo_web.common.Constant;
import okhttp3.*;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class HttpUtil {

    /**
     * @param data 返回的99数据
     * @return 返回challenge
     * @Deprecated 初始化
     */
    public static HashMap<String, String> initSlider(String data, String token, String ticket) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("capToken", token);
        hashMap.put("language", "zho");
        hashMap.put("reqId", data);
        String s = UUID.randomUUID().toString().replaceAll("-", "");
        hashMap.put("sid", s);
        hashMap.put("action", "risk.captcha.init");
        hashMap.put("systemCode", "62");
        hashMap.put("version", "6.73.0");
        hashMap.put("token", token);
        hashMap.put("clientId", "");
        hashMap.put("ticket", ticket);

        String encrypt = null;
        try {

            encrypt = EncryptionUtil.encrypt(JSONObject.toJSONString(hashMap));
        } catch (Exception e) {
            e.printStackTrace();
        }
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, encrypt);
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("https://marketingapi.hellobike.com/api")
                .post(body)
                .addHeader("Host", "api.hellobike.com")
                .addHeader("sid", s)
                .addHeader("user-agent", "")
                .addHeader("inner_action", "risk.captcha.init")
                .addHeader("systemcode", "62")
                .addHeader("chaos", "true")
                .addHeader("content-type", "application/json; charset=UTF-8")
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = Constant.client.newCall(request).execute();
            // 解密原文
            String decrypt = EncryptionUtil.decrypt(response.body().string());
            JSONObject jsonObject = JSONObject.parseObject(decrypt);
            String string = jsonObject.getString("data");
            JSONObject dataJson = JSONObject.parseObject(string);
            if (dataJson == null)
                return null;
            String challenge = dataJson.getString("challenge");
            String captchaId = dataJson.getString("captchaId");
            HashMap<String, String> resutMap = new HashMap<>();
            resutMap.put("challenge", challenge);
            resutMap.put("captchaId", captchaId);

            return resutMap;
        } catch (Exception e) {
        }
        return null;
    }


    public static String callBack(HashMap<String, String> dataMap) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("capToken", dataMap.get("capToken"));
        hashMap.put("captchaOutput", dataMap.get("captcha_output"));
        hashMap.put("challenge", dataMap.get("challenge"));
        hashMap.put("genTime", dataMap.get("gen_time"));
        hashMap.put("lotNumber", dataMap.get("lot_number"));
        hashMap.put("passToken", dataMap.get("pass_token"));
        hashMap.put("reqId", dataMap.get("reqId"));
        hashMap.put("riskType", "");
        String s = UUID.randomUUID().toString().replaceAll("-", "");
        hashMap.put("sid", s);
        hashMap.put("systemCode", "62");
        hashMap.put("action", "risk.captcha.check");
        hashMap.put("version", "6.73.0");
        hashMap.put("token", dataMap.get("capToken"));
        hashMap.put("clientId", "");
        hashMap.put("ticket", dataMap.get("ticket"));
        MediaType mediaType = MediaType.parse("application/json");
        String encrypt;
        try {
            encrypt = EncryptionUtil.encrypt(JSONObject.toJSONString(hashMap));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        RequestBody body = RequestBody.create(mediaType, encrypt);
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("https://marketingapi.hellobike.com/api")
                .post(body)
                .addHeader("Host", "api.hellobike.com")
                .addHeader("sid", "")
                .addHeader("user-agent", "Mozilla/5.0 (Linux; Android 8.1.0; Redmi 5 Build/OPM1.171019.026; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0")
                .addHeader("inner_action", "risk.captcha.check")
                .addHeader("systemcode", "62")
                .addHeader("chaos", "true")
                .addHeader("content-type", "application/json; charset=UTF-8")
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = Constant.client.newCall(request).execute();
            // 解密原文
            String decrypt = EncryptionUtil.decrypt(response.body().string());
            JSONObject jsonObject = JSONObject.parseObject(decrypt);
            System.out.println("jsonObject = " + jsonObject);
            String msg = jsonObject.getString("msg");
            String success = jsonObject.getString("data");
            JSONObject successData = JSONObject.parseObject(success);
            System.out.println(Constant.format.format(new Date()) + ":"  + jsonObject);
            if (msg.equals("ok") && successData.getString("success").equals("1")) {
                System.out.println("处理图形验证成功");
                return "处理图形验证成功";
            }
            System.out.println("处理图形验证失败");
            return "处理图形验证失败";
        } catch (Exception e) {
        }
        System.out.println("处理图形验证失败");
        return "处理图形验证失败";
    }

    /**
     * @param url 请求地址
     * @Deprecated 同步GET无参请求
     */
    public static String doGet1(String url) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = okHttpClient.newCall(request).execute();
        return response.body().string();
    }


    public static HashMap<String, String> getCodePostBL(String id, int number) {
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("captcha_id", id);
        hashMap.put("proxy", Constant.IP_ADDRESS);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("http://" + Constant.IP_SERVER[number] + "/JyApi/slide")
                .post(body)
                .build();
        System.out.println("百里使用的IP是:" + Constant.IP_SERVER[number]);
        Constant.NUMBER_BL++;
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            // 解密原文
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            JSONObject dataJson = jsonObject.getJSONObject("data");
            JSONObject seccode = JSONObject.parseObject(dataJson.getString("seccode"));
            String lotNumber = seccode.getString("lot_number");
            String passToken = seccode.getString("pass_token");
            String genTime = seccode.getString("gen_time");
            String captchaOutput = seccode.getString("captcha_output");
            // 封准需要的数据
            HashMap<String, String> codeData = new HashMap<>();
            codeData.put("captcha_output", captchaOutput);
            codeData.put("gen_time", genTime);
            codeData.put("lot_number", lotNumber);
            codeData.put("pass_token", passToken);
            return codeData;
        } catch (Exception e) {
            return null;
        }
    }



    public static String getIpAddress(String ipNumber) {
        ArrayList<String> ipList = new ArrayList<>();

        String url = "http://api2.xkdaili.com/tools/XApi.ashx?apikey=XK00CE13196F4A48C915&qty=" + ipNumber + "&format=json&split=0&sign=6ae82543fc3d5cad19ecc7c22efe21a7";
        String result = null;
        try {
            result = doGet1(url);
        } catch (IOException e) {
            return null;
        }

        return result;
    }


    public static String txm(String ticket,String token,String reqId,String SerUrl,String proxy,String host) {
        OkHttpClient client = new OkHttpClient();
        Constant.NUMBER_BL++;
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("ticket", ticket);
        hashMap.put("token",token);
        hashMap.put("reqId", reqId);
        hashMap.put("SerUrl",SerUrl);
        hashMap.put("proxy", proxy);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url(host)
                .post(body)
                .addHeader("content-type", "application/json; charset=UTF-8")
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            String string = response.body().string();
            if (string.equals("true"))
            {
                return "处理图形验证成功";
            }else {
                return "处理图形验证失败";
            }
        } catch (Exception e) {

        }
        System.out.println("处理图形验证失败");
        return "处理图形验证失败";
    }


}
